<template>
  <section>
    <p>
      回答一个是/否问题：
      <input v-model="question">
    </p>
    <p>{{answer}}</p>
  </section>
</template>

<script>
import axios from "axios";
import _ from "lodash";

export default {
  name: "Watch",
  data() {
    return {
      question: "",
      answer: "除非你问问题，否则我不能给你答案!"
    };
  },
  watch: {
    question() {
      this.answer = "等着你停止打字…";
      this.getAnswer();
    }
  },
  created() {
    this.getAnswer = _.debounce(this.getAnswer, 500);
  },
  methods: {
    getAnswer: function() {
      if (this.question.indexOf("?") === -1) {
        this.answer = "问题通常包含一个问号。:-)";
        return;
      }
      this.answer = "正在思考...";
      var vm = this;
      axios
        .get("https://yesno.wtf/api")
        .then(function(response) {
          vm.answer = _.capitalize(response.data.answer);
        })
        .catch(function(error) {
          vm.answer = "错误!无法访问API。" + error;
        });
    }
  }
};
</script>